package smy.att;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;

import smy.att.devices.ISimulator;

public class ADB {
	protected String ADB_path = "adb";
	protected ISimulator simulator;

	public String Shell(String ... args) {
		String result = Command(Helper.Join("shell" , args));
		System.out.println("The command for " + args[0] + " is");
		System.out.println(result);
		return result;
	}
	
	public void Pull(String path, String localPath) {
		String result = Command("pull", path, localPath);
		// If success will occurs "xxx in x seconds"
		if (!result.contains("in")) 
		{
			throw new RuntimeException("Pull Error");
		}
	}
	
	public void Push(String path, String localPath) {
		String result = Command("push", localPath, path);
		// If success will occurs "xxx in x seconds"
		if (!result.contains("in")) 
		{
			throw new RuntimeException("Push Error + \n" + result);
		}
	}
	
	public void Install(AndroidApplication apk) {
		Command("install", apk.path);
	}
	
	public void Uninstall(AndroidApplication apk) {
		Command("uninstall", apk.PackageName());
	}
	
	public void Start(AndroidApplication apk) {
		String result = Command("shell", "am", "start", "-n", apk.PackageName() + "/" + apk.MainActivityName());
		if (result.contains("Error"))
		{
			throw new RuntimeException("Cannot Start Application\n" + result);
		}
	}
	
	public String Command(String ... args) {
		try {
			Runtime rt = Runtime.getRuntime();
			ProcessBuilder builder = new ProcessBuilder(Helper.Join(new String[]{ADB_path , "-s" , simulator.Name()}, args));
			builder.redirectErrorStream(true);
			builder.directory(new File("."));
			Process process = builder.start();
			(new OutputStreamWriter(process.getOutputStream())).write("\n");
			String  result  = Helper.ReadInputStream(process.getInputStream());
			return  result;
		} catch (IOException e) {
			System.out.println(e.toString());
			throw new RuntimeException("Error While Connect To ADB, Please Make Sure ADB is In Your Path");
		}
	}
	
	public void Unlock() {
		Shell("input" , "keyevent" , "82");
	}
	
	static public ADB Builder(ISimulator simulator) {
		ADB adb = new ADB();
		adb.simulator = simulator;
		simulator.Connect(adb);
		return adb;
	}
}
